package com.lagou.service.impl;

import com.lagou.domain.User;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author junbao
 * 基于数据库完成认证
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("user not found, " + username);
        }
        // 权限的集合
        Collection<? extends GrantedAuthority> authorities = new ArrayList<>();

        UserDetails userDetails = new org.springframework.security.core.userdetails.User
                (username, "{bcrypt}" + user.getPassword(),
                        true,
                        true,
                        true,
                        true,
                        authorities);
        return userDetails;
    }
}
